package com.yangxk.kadmin.web.common.listener;

import com.yangxk.kadmin.common.util.ValidUtil;
import com.yangxk.kadmin.web.common.Const;
import com.yangxk.kadmin.web.module.system.po.Auth;
import com.yangxk.kadmin.web.module.system.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 权限初始化监听器
 * 在项目启动后加载所有权限信息
 *
 * @author yangxk
 * @date 2018/10/19 16:36
 */
@Component
public class AuthInitListener implements ApplicationListener, ServletContextAware {

    private ServletContext servletContext;

    @Autowired
    private AuthService authService;

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof ContextRefreshedEvent) {
            List<Auth> authList = authService.queryAllAuth();
            // key为url, value为auth_code
            Map<String, String> collect = authList.stream().filter(item -> !ValidUtil.isEmpty(item.getUrl()))
                    .collect(Collectors.toMap(Auth::getUrl, Auth::getAuthCode));
            servletContext.setAttribute(Const.CONTEXT_AUTH_KEY, collect);
        }
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}
